package com.bantang.utils;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.support.ExcelTypeEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Excel相关工具类
 */
@Slf4j
public class ExcelUtils {

    public static String excelToCsv(MultipartFile multipartFile) {
        File file = null;
//        try {
//            file = ResourceUtils.getFile("classpath:网站数据.xlsx");
//        } catch (FileNotFoundException e) {
//            e.printStackTrace();
//        }
        List<Map<Integer, String>> list = null;
        try {
            list = EasyExcel.read(multipartFile.getInputStream())
                        .excelType(ExcelTypeEnum.XLSX)
                        .sheet()
                        .headRowNumber(0)
                        .doReadSync();
        } catch (IOException e) {
            log.error("表格处理错误");
            e.printStackTrace();
        }

        if (CollUtil.isEmpty(list)){
            return "";
        }

        LinkedHashMap<Integer,String> headMap = (LinkedHashMap<Integer, String>) list.get(0);

        List<String> headList = headMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());

        String head = StrUtil.join(",",headList);

        StringBuilder result = new StringBuilder();
        result.append(head).append("\n");

        //读取每一行数据
        for (int i = 1; i < list.size(); i++) {
            LinkedHashMap<Integer,String> dataMap = (LinkedHashMap<Integer, String>) list.get(i);
            List<String> dataList = dataMap.values().stream().filter(ObjectUtils::isNotEmpty).collect(Collectors.toList());

            String data = StrUtil.join(",",dataList);
            result.append(data).append("\n");
        }
            return result.toString();
    }

    public static void main(String[] args) {
        String result = excelToCsv(null);
        System.out.println(result);
    }
}
